const requestHelper = require('../../utils/request');
const buildUrl = requestHelper.buildUrl || ((url) => url);

Page({
  data: {
    phone: '',
    smsCode: '',
    newPassword: '',
    confirmPassword: '',
    sending: false,
    countdown: 0
  },

  onLoad() { },

  onPhoneInput(e) {
    this.setData({ phone: e.detail.value.trim() });
  },

  onCodeInput(e) {
    this.setData({ smsCode: e.detail.value.trim() });
  },

  onPwdInput(e) {
    this.setData({ newPassword: e.detail.value });
  },

  onPwdConfirmInput(e) {
    this.setData({ confirmPassword: e.detail.value });
  },

  // 发送验证码
  sendCode() {
    if (this.data.sending || this.data.countdown > 0) return;
    const phone = this.data.phone;
    if (!/^1\d{10}$/.test(phone)) {
      wx.showToast({ title: '请输入正确手机号', icon: 'none' });
      return;
    }

    this.setData({ sending: true });

    wx.request({
      url: buildUrl('/api/auth/send-sms'),
      method: 'POST',
      data: { phone },
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        const data = res.data || {};
        if (data.success) {
          wx.showToast({ title: '验证码已发送', icon: 'success' });
          this.startCountdown();
        } else {
          wx.showToast({ title: data.message || '发送失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
      },
      complete: () => {
        this.setData({ sending: false });
      }
    });
  },

  startCountdown() {
    this.setData({ countdown: 60 });
    const timer = setInterval(() => {
      const t = this.data.countdown - 1;
      if (t <= 0) {
        clearInterval(timer);
        this.setData({ countdown: 0 });
      } else {
        this.setData({ countdown: t });
      }
    }, 1000);
  },

  // 提交修改密码
  submit() {
    const { phone, smsCode, newPassword, confirmPassword } = this.data;

    if (!/^1\d{10}$/.test(phone)) {
      wx.showToast({ title: '请输入正确手机号', icon: 'none' });
      return;
    }
    if (!smsCode) {
      wx.showToast({ title: '请输入验证码', icon: 'none' });
      return;
    }
    if (!newPassword || newPassword.length < 6) {
      wx.showToast({ title: '密码至少6位', icon: 'none' });
      return;
    }
    if (newPassword !== confirmPassword) {
      wx.showToast({ title: '两次密码不一致', icon: 'none' });
      return;
    }

    wx.showLoading({ title: '提交中...' });

    wx.request({
      url: buildUrl('/api/auth/reset-password-with-sms'),
      method: 'POST',
      data: { phone, smsCode, newPassword },
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        const data = res.data || {};
        if (data.success) {
          wx.showToast({ title: '密码修改成功，请重新登录', icon: 'success' });

          // 清除本地登录状态并强制跳转到登录页
          setTimeout(() => {
            try {
              wx.clearStorageSync();
            } catch (e) { }

            const app = getApp && getApp();
            if (app && app.globalData) {
              app.globalData.userId = null;
              app.globalData.userRole = null;
              app.globalData.isLoggedIn = false;
            }

            wx.reLaunch({ url: '/pages/login/login' });
          }, 800);
        } else {
          wx.showToast({ title: data.message || '修改失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  }
});
